package com.offcn.user.controller;

import com.offcn.utils.FastDFSClient;
import com.offcn.utils.ResultMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: FileController
 * @Description: 文件上传下载控制层
 * @Date: 2020/12/7 19:46
 */
@Controller
@RequestMapping("/file")
public class FileController {
    @Value("${uploadDir}")
    private String uploadDir;
    /**
     * 文件上传
     * @param upload
     * @param session
     * @return
     */
    @PostMapping("/upload")
    public String uploadFile(MultipartFile upload, HttpSession session){
        try {
            //1.获取文件原始名
            String filename = upload.getOriginalFilename();
            //2.创建文件对象
            File saveFile=new File(uploadDir);
            //3.判断文件是否存在
            if(!saveFile.exists()){
                saveFile.mkdirs();
            }
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
            String format = sdf.format(new Date());
            File file=new File(saveFile, "\\"+format+filename);
            System.out.println(file);
            upload.transferTo(file);
            session.setAttribute("message", "文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            session.setAttribute("message", "文件上传失败");
        }
        return "redirect:/success.jsp";
    }
    @Value("${FILE_SERVER_URL}")
    private String FILE_SERVER_URL;
    @PostMapping("/uploadPic")
    public ResultMap uploadPic(MultipartFile pic){
        try {
            //1.获取文件原始文件名
            String filename = pic.getOriginalFilename();
            System.out.println(filename);
            //2.获取后缀名
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            //3.创建一个FastDfs的客户端
            FastDFSClient fastDFSClient=new FastDFSClient("classpath:config/fdfs_client.conf");
            //4.上传图片
            String path = fastDFSClient.uploadFile(pic.getBytes(), extName);
            System.out.println(path);
            //5.拼接返回的url和ip地址，
            String url=FILE_SERVER_URL+path;
            return new ResultMap(true, url);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMap(false,"上传失败");
        }
    }
}
